package com.epam.manager.controller;

import javax.faces.model.DataModel;

import com.epam.DAO.BillDAO;
import com.epam.DAO.CarDAO;
import com.epam.entity.Bill;
import com.epam.entity.Car;
import com.epam.entity.Request;
import com.epam.entity.Status;

public class NewRequestManagedBean extends RequestController {

	private BillDAO billDAO;
	private CarDAO carDAO;

	private Request request;

	private int page = 1;
	
	public NewRequestManagedBean() {
		super();
		carDAO = daoFactory.getCarDAO();
		billDAO = daoFactory.getBillDAO();
	}

	public Request getRequest() {
		return request;
	}

	public void setRequest(Request request) {
		this.request = request;
	}

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}
	
	@Override
	public DataModel<Request> getRequests() {
		requests.setWrappedData(requestDAO.getRequests(Status.NEW));
		return requests;
	}

	public void initRequest() {
		request = requests.getRowData();
	}

	public void cancelRequest() {
		request.setStatus(Status.CANCELLED);
		requestDAO.update(request);

		Car car = request.getCar();
		car.setIsAvaliable(true);
		carDAO.update(car);
	}

	public void approveRequest() {
		request.setStatus(Status.APPROVED);

		long days = (request.getEndDate().getTime() - request.getBeginDate()
				.getTime()) / (1000 * 60 * 60 * 24);

		double sum = request.getCar().getRentRate() * days;
		sum *= 100;
		sum = (double) Math.round(sum) / 100;

		Bill bill = new Bill(request, sum, Status.NOT_PAYED, "RENT PAYMENT");
		billDAO.create(bill);

		requestDAO.update(request);
	}

}
